﻿using glTech.Log4netWrapper;
using Nancy.Hosting.Self;
using RESTFinder.Service.Repositories;
using RESTFinder.Service.Utils;
using System;
using System.ServiceProcess;
using System.Threading;

namespace RESTFinder.Service
{
    public partial class RESTFinderService : ServiceBase
    {
        private Thread _thread;
        private bool _isStop;

        public RESTFinderService()
        {
            var appRepository = new AppRepository();
            InitializeComponent();
            try
            {
                var nancyPort = appRepository.AppConfigModel.NancyPort;
                var rootPath = appRepository.AppConfigModel.RootPath;
                StartNancyHost(rootPath, nancyPort);
            }
            catch (Exception ex)
            {
                Logger.LogError4Exception(ex);
            }
        }

        protected override void OnStart(string[] args)
        {
            try
            {
                _isStop = false;
                _thread = new Thread(ThreadMain)
                {
                    Name = "REST Finder"
                };

                _thread.Start();
            }
            catch (Exception ex)
            {
                Logger.LogError4Exception(ex);
            }
        }

        /// <summary>
        /// 启动Nancy服务
        /// </summary>
        private void StartNancyHost(string rootPath,int portNO = 8080)
        {
            try
            {
                var hostConfiguration = new HostConfiguration
                {
                    UrlReservations = new UrlReservations() { CreateAutomatically = true }
                };
                string URL = string.Format("http://localhost:{0}", portNO);

                var nancyHost = new NancyHost(new RestBootstrapper(rootPath),hostConfiguration, new Uri(URL));
                nancyHost.Start();
            }
            catch (Exception ex)
            {
                Logger.LogError("启动NancyHost失败.");
                Logger.LogError4Exception(ex);
            }
        }

        private void ThreadMain()
        {
            while (!_isStop)
            {
                try
                {
                    Console.WriteLine(PathUtil.GetLog4netPath());
                   
                }
                catch (Exception ex)
                {
                    Logger.LogError4Exception(ex);
                }
              
                Thread.Sleep(1000);
            }
        }

        protected override void OnStop()
        {
            _isStop = true;
            _thread.Join();
        }
    }
}
